package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.bean.BeanValidators;
import com.ruoyi.common.core.utils.bean.DateRanger;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.*;
import com.ruoyi.system.filter.AuthDataFilter;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.babyfish.jimmer.sql.JSqlClient;
import org.babyfish.jimmer.sql.ast.mutation.SaveMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.Validator;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
@RequiredArgsConstructor
public class SysUserServiceImpl implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    @Lazy
    private ISysConfigService configService;
    private final ISysDeptService deptService;
    protected final Validator validator;
    private final JSqlClient sqlClient;

    @Override
    public long getCurrentUserId() {
        return SecurityUtils.getUserId();
    }

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUser> selectUserList(SysUserListInput user, DateRanger dateRanger) {
        SysUserTable table = SysUserTable.$;
        SysUserFetcher fetcher = SysUserFetcher.$
                .allScalarFields()
                .deptId()
                .dept(SysDeptFetcher.$.deptName());
        return sqlClient.createQuery(table)
                .where(table.userName().ilikeIf(user.getUserName()),
                        table.phonenumber().ilikeIf(user.getPhonenumber()),
                        table.status().eqIf(user.getStatus()),
                        table.deptId().eqIf(user.getDeptId()),
                        table.createTime().betweenIf(DateRanger.isAllNotEmpty(dateRanger), dateRanger.getBeginTime(), dateRanger.getEndTime())
                ).select(table.fetch(
                        fetcher
                ))
                .execute();
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUser> selectAllocatedList(SysUserAllocatedRoleInput user) {
        SysUserTable table = SysUserTable.$;
        return sqlClient.createQuery(table)
                .where(table.userName().ilikeIf(user.getUserName()),
                        table.phonenumber().ilikeIf(user.getPhonenumber()),
                        table.asTableEx().roles().roleId().eq(user.getRoleId()))
                .select(table.fetch(
                        SysUserFetcher.$.allScalarFields()
                                .deptId()
                )).execute();
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUser> selectUnallocatedList(SysUserAllocatedRoleInput user) {
        SysUserTable table = SysUserTable.$;
        // 获取角色已分配用户，排除已经分配的用户
        List<Long> notInUserIdList = sqlClient.createQuery(table)
                .where(table.asTableEx().roles().roleId().eq(user.getRoleId()))
                .select(table.userId()).execute();
        return sqlClient.createQuery(table)
                .where(table.userName().ilikeIf(user.getUserName()),
                        table.phonenumber().likeIf(user.getPhonenumber()),
                        table.userId().notInIf(notInUserIdList)
                )
                .select(table.fetch(SysUserFetcher.$.allScalarFields()))
                .execute();
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        SysUserTable table = SysUserTable.$;
        SysUser sysUser = sqlClient.filters(it -> it.disableByTypes(AuthDataFilter.class))
                .createQuery(table).where(table.userName().eq(userName))
                .select(
                        table.fetch(SysUserFetcher.$.allScalarFields()
                                .delFlag()
                                .deptId()
                                .dept(SysDeptFetcher.$.allScalarFields())
                                .roles(SysRoleFetcher.$.allScalarFields()
                                        .menus(SysMenuFetcher.$.allScalarFields())
                                )
                        )).fetchOneOrNull();
        return sysUser;
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
        return sqlClient.findById(SysUserFetcher.$.allScalarFields()
                        .postIds()
                        .roleIds()
                        .deptId()
                , userId);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        SysRoleTable table = SysRoleTable.$;
        List<SysRole> list = sqlClient.createQuery(table)
                .where(table.asTableEx().users().userName().eq(userName))
                .select(table.fetch(SysRoleFetcher.$.allScalarFields()))
                .execute();
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::roleName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        SysPostTable table = SysPostTable.$;
        List<SysPost> list = sqlClient.createQuery(table)
                .where(table.asTableEx().users().userName().eq(userName))
                .select(table.fetch(SysPostFetcher.$.allScalarFields()))
                .execute();
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPost::postName).collect(Collectors.joining(","));
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param username 用户名
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(Long userId, String username) {
        SysUserTable table = SysUserTable.$;
        SysUser info = sqlClient.createQuery(table).where(table.userName().eq(username)).select(table.fetch(SysUserFetcher.$.allScalarFields())).fetchOneOrNull();
        if (StringUtils.isNotNull(info) && info.userId() != userId) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param phonenumber 用户信息
     * @return
     */
    @Override
    public boolean checkPhoneUnique(Long userId, String phonenumber) {
        SysUserTable table = SysUserTable.$;
        SysUser info = sqlClient.createQuery(table).where(table.phonenumber().eq(phonenumber)).select(table.fetch(SysUserFetcher.$.allScalarFields())).fetchOneOrNull();
        if (StringUtils.isNotNull(info) && info.userId() != userId) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param userId 用户信息
     * @param email  用户信息
     * @return
     */
    @Override
    public boolean checkEmailUnique(Long userId, String email) {
        SysUserTable table = SysUserTable.$;
        SysUser info = sqlClient.createQuery(table).where(table.email().eq(email)).select(table.fetch(SysUserFetcher.$.allScalarFields())).fetchOneOrNull();
        if (StringUtils.isNotNull(info) && info.userId() != userId) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param userId 用户信息
     */
    @Override
    public void checkUserAllowed(Long userId) {
        if (SecurityUtils.isAdmin(userId)) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId) {
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            SysUser user = SysUserDraft.$.produce(draft -> draft.setUserId(userId));
            List<SysUser> users = selectUserList(new SysUserListInput(user), new DateRanger());
            if (StringUtils.isEmpty(users)) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUserSaveInput user) {
        SysUser sysUser = SysUserDraft.$
                .produce(user.toEntity(), draft ->
                        draft.applyCreateBy(userDraft ->
                                userDraft.setUserId(SecurityUtils.getUserId())));
        return sqlClient.saveCommand(sysUser)
                .setMode(SaveMode.INSERT_ONLY)
                .execute()
                .getTotalAffectedRowCount();
    }


    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user) {
        return sqlClient.saveCommand(user)
                .setMode(SaveMode.INSERT_ONLY)
                .execute()
                .getTotalAffectedRowCount() > 0;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUserUpdateInput user) {
        SysUser sysUser = SysUserDraft.$
                .produce(draft ->
                        draft.applyUpdateBy(userDraft ->
                                userDraft.setUserId(SecurityUtils.getUserId())));
        return sqlClient.saveCommand(sysUser)
                .setMode(SaveMode.UPDATE_ONLY)
                .execute()
                .getTotalAffectedRowCount();
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public void insertUserAuth(Long userId, Long[] roleIds) {
        SysUserTable table = SysUserTable.$;
        List<Long> oldRoleIds = sqlClient.createQuery(table)
                .where(table.userId().eq(userId))
                .select(table.fetch(SysUserFetcher.$.allScalarFields().roleIds())).fetchOne().roleIds();
        sqlClient.getAssociations(SysUserProps.ROLES)
                .deleteAllCommand(Collections.singletonList(userId), oldRoleIds)
                .execute();
        sqlClient.getAssociations(SysUserProps.ROLES)
                .saveAllCommand(Collections.singletonList(userId), Arrays.asList(roleIds))
                .ignoreConflict(true)
                .execute();
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUserStatusInput user) {
        return sqlClient.saveCommand(user.toEntity())
                .setMode(SaveMode.UPDATE_ONLY)
                .execute().getTotalAffectedRowCount();
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUserCacheDTO user) {
        return sqlClient.saveCommand(user.toEntity())
                .setMode(SaveMode.UPDATE_ONLY)
                .execute()
                .getTotalAffectedRowCount();
    }

    /**
     * 修改用户头像
     *
     * @param userId 用户ID
     * @param avatar 头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(Long userId, String avatar) {
        SysUser sysUser = SysUserDraft.$.produce(draft ->
                draft.setUserId(userId)
                        .setAvatar(avatar)
        );
        return sqlClient.saveCommand(sysUser)
                .setMode(SaveMode.UPDATE_ONLY)
                .execute()
                .getTotalAffectedRowCount() > 0;
    }


    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUserResetPwdInput user) {
        return sqlClient.saveCommand(user.toEntity())
                .setMode(SaveMode.UPDATE_ONLY)
                .execute()
                .getTotalAffectedRowCount();
    }

    /**
     * 重置用户密码
     *
     * @param userId   用户ID
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(Long userId, String password) {
        SysUser sysUser = SysUserDraft.$.produce(draft ->
                draft.setUserId(userId)
                        .setPassword(password)
                        .setPwdUpdateDate(new Date()));
        return sqlClient.saveCommand(sysUser)
                .setMode(SaveMode.UPDATE_ONLY)
                .execute()
                .getTotalAffectedRowCount();
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     *//*
    public void insertUserRole(SysUser user) {
        this.insertUserRole(user.userId(), user.roles().toArray(Long[]::new));
    }

    *//**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     *//*
    public void insertUserPost(SysUser user) {
        Long[] posts = user.postIds().toArray(new Long[user.postIds().size()]);
        if (StringUtils.isNotEmpty(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>(posts.length);
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.userId());
                up.setPostId(postId);
                list.add(up);
            }
            userPostMapper.batchUserPost(list);
        }
    }

    *//**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     *//*
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

    *//**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     *//*
    @Override
    @Transactional
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    */

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(long[] userIds) {
        List<Long> userIdList = Arrays.stream(userIds)
                .boxed().collect(Collectors.toList());
        return sqlClient.deleteByIds(SysUser.class, userIdList)
                .getTotalAffectedRowCount();
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    @Override
    public String importUser(List<SysUserExportExcel> userList, Boolean isUpdateSupport) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (SysUserExportExcel user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = this.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, user);
                    deptService.checkDeptDataScope(user.getDeptId());
//                    String password = configService.selectConfigByKey("sys.user.initPassword");
//                    user.setPassword(SecurityUtils.encryptPassword(password));
                    sqlClient.saveCommand(user.toEntity()).setMode(SaveMode.INSERT_ONLY).execute();
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, user);
                    checkUserAllowed(u.userId());
                    checkUserDataScope(u.userId());
                    deptService.checkDeptDataScope(user.getDeptId());
                    user.setUserId(u.userId());
                    sqlClient.saveCommand(user.toEntity()).setMode(SaveMode.UPDATE_ONLY).execute();
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public Boolean updateUserRecordLogin(SysUserRecordLoginInput user) {
        return sqlClient.saveCommand(user.toEntity())
                .setMode(SaveMode.UPDATE_ONLY)
                .execute()
                .getTotalAffectedRowCount() > 0;
    }
}
